<template>
  <div>
    <!--表格-->
    <el-table
      :data="tableData"
      border
      ref="tplTable"
      :highlight-current-row="selectType === 'single'"
      @current-change="handleSingleSelect"
      @selection-change="handleMultipleSelect"
      @row-dblclick="dblclick"
      @header-click="sortColumn"
      @sort-change="sortChange"
      :row-style="rowStyle"
      :cell-style="cellStyle"
      :height="tHeight"
      v-loading="isLoading"
      class="tableGroup"
      style="width: 100%;">
      <el-table-column v-if="showIndex"
                       type="index"
                       label="序号"
                       prop="index"
                       align="center"
                       sortable
                       width="50">
      </el-table-column>
      <el-table-column v-if="selectType === 'multiple'"
                        type="selection"
                        align="center"
                        width="50">
      </el-table-column>
      <el-table-column v-for="item in columnInfo"
                       :key="item.code"
                       :sortable="item.sorttable"
                       :prop="item.code"
                       :label="item.title"
                       :width="item.width"
                       :header-align="item.headerAlign"
                       :align="item.align">
        <template slot-scope="scope">
          <!-- 为了兼容自定义html代码-->
          <p v-if="item.hasOwnProperty('format') && item['format']!=null && item['format']!='undefined' && typeof item['format']=='function'" v-html='item.format(scope.row, scope.column, scope.row[item.code])'></p>
          <p v-else v-html="scope.row[item.code]"></p>
          <el-row v-if="item.hasOwnProperty('btns') && item['btns'].length>0" style="padding-top: 0">
            <el-button v-for="btn in item.btns" v-if="btn.showByRow(scope.row) || btn.showByRow(scope.row)=='undefined'" :key="btn.label" :size="btn.size" :type="btn.type" :style="btn.style" :disabled="btn.disabled" @click="btn.action(scope.row)">{{btn.label}}</el-button>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <div class="page-bar" v-if="Object.keys(pageInfo).length > 0 && tableData && tableData.length>0">
      <div class="paging-left">显示{{curFirst}}到{{curLast}}，共{{pageInfo.total}}条记录</div>
      <div class="paging-right">
        <el-select v-model="pageInfo.pageSize"
                   placeholder="请选择"
                   style="width: 96px"
                   @change="pagingChange">
          <el-option
            v-for="item in sizeList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <!--<el-input v-model.number="pageInfo.pageSize" class="paging-size" @keyup.enter.native="pagingSize"></el-input>-->
        <img src="/src/assets/pageBar/paging-first.png" alt="第一页" :class="[isFirst?'disable':'enable']" @click="firstPage"/>
        <img src="/src/assets/pageBar/paging-previous.png" alt="上一页" :class="[isPrev?'disable':'enable']" @click="prevPage"/>
        第&#12288;<input v-model="pageInfo.currentPage" class="paging-size" @keyup.enter="pagingChange"/>&#12288;页，共&#8194;{{pageInfo.pageCount}}&#8194;页
        <img src="/src/assets/pageBar/paging-next.png" alt="下一页" :class="[isNext?'disable':'enable']" @click="nextPage"/>
        <img src="/src/assets/pageBar/paging-last.png" alt="最后一页" :class="[isLast?'disable':'enable']" @click="lastPage"/>
        <img src="/src/assets/pageBar/paging-fresh.png" alt="刷新" @click="refreshPage"/>
      </div>

      <!--<el-pagination
        @current-change="handlePageChange"
        @prev-click="prevClick"
        @next-click="nextClick"
        @size-change="sizeChangeClick"
        align="center"
        background
        layout="total,sizes, prev, pager, next,jumper"
        prev-text="上一页"
        next-text="下一页"
        :page-sizes="pageInfo.sizes"
        :page-count="pageInfo.pageCount"
        :page-size="pageInfo.pageSize"
        :current-page="pageInfo.currentPage"
        :total="pageInfo.total">
      </el-pagination>-->
    </div>
  </div>
</template>

<script>
  import { mapGetters } from "vuex";
  export default {
    name: "Table",
    computed: {
      ...mapGetters(["workAreaHeight"])
    },
    props: {
      tHeight: {
        type: String,
        default: function () {
          return this.workAreaHeight;
        }
      },
      //列表数据源
      tableData: {
        type: Array,
        default: function () {
          return []
        }
      },
      //
      columnInfo: {
        type: Array,
        default: function () {
          return []
        }
      },
      //对象，不传表示没有分页,包含三个参数,均必填pageSize：每页展示的条数。currentPage：当前页码。pageCount：总页数
      pageInfo: {
        type: Object,
        default: function () {
          return {}
        }
      },
      cellStyle: {
        type: Object,
        default: function () {
          return {}
        }
      },
      rowStyle: {
        type: Object,
        default: function () {
          return {}
        }
      },
      //single:单行选中 multiple:多行选中 否则无需传此字段
      selectType:{
        type:String,
        default:function () {
          return ''
        }
      },
      showIndex: {//是否显示序号列
        type: Boolean,
        default: function () {
          return false;
        }
      },
      dblclick: { //行双击事件
        type: Function,
        default: function () {
        }
      },
      sortColumn: { //表头点击事件
        type: Function,
        default: function () {
        }
      }
    },
    data() {
      return {
        curLast:null,
        curFirst:null,
        isLoading:true,
        orderCode: "",
        orderBy: "",
        isFirst:true,
        isPrev:true,
        isNext:this.pageInfo.currentPage===this.pageInfo.pageCount,
        isLast:this.pageInfo.currentPage===this.pageInfo.pageCount,
        sizeList:[
          {label:'5条/页',value:5},
          {label:'10条/页',value:10},
          {label:'15条/页',value:15},
          {label:'20条/页',value:20},
        ]
      }
    },
    watch:{
      tableData: {
        handler(newValue, oldValue) {
          for (let i = 0; i < newValue.length; i++) {
            if (oldValue[i] != newValue[i]) {
              this.tableData = newValue;
            }
          }
        },
        deep: true
      },
      pageInfo: {
        handler(newValue, oldValue) {
          this.pageInfo=newValue;
          this.changeBarStatus();
        },
        deep: true
      }
    },
    created(){
      for(let i=0;i<this.columnInfo.length;i++){
        if(!this.columnInfo[i].headerAlign){
          this.columnInfo[i].headerAlign = "left";//所有表头默认使用居左显示
        }
        if(this.columnInfo[i].sorttable){
          this.columnInfo[i].sorttable = "custom";//为了兼容组件使用传值，把true都改为"custom"用来实现后端排序
        }
      }
      if(this.pageInfo && this.pageInfo.sizes && this.pageInfo.sizes.length>0){
        this.sizeList = [];
        for(let i=0;i<this.pageInfo.sizes.length;i++){
          this.sizeList.push({
            label: this.pageInfo.sizes[i] + "条/页",
            value: this.pageInfo.sizes[i]
          })
        }
      }
    },
    mounted(){
      this.changeBarStatus();
      this.isLoading=false;
    },
    methods:{
      /*页码改变时，状态栏的显示变化*/
      changeBarStatus(){
        if(!/^[1-9]\d*$/.test(this.pageInfo.currentPage)) return;
        if(this.pageInfo.total < this.pageInfo.pageSize * this.pageInfo.currentPage)
          this.curLast = this.pageInfo.total;
        else
          this.curLast = this.pageInfo.pageSize * this.pageInfo.currentPage;

        this.curFirst = this.pageInfo.currentPage > this.pageInfo.pageCount
                        ? (this.pageInfo.pageCount-1)*this.pageInfo.pageSize+1
                        : (this.pageInfo.currentPage-1)*this.pageInfo.pageSize+1;

        this.pageInfo.pageCount = Math.ceil(this.pageInfo.total/this.pageInfo.pageSize); //总页数
        //控制鼠标状态
        if(this.pageInfo.currentPage === 1){
          this.isFirst=true;
          this.isPrev=true;
        }else{
          this.isFirst=false;
          this.isPrev=false;
        }
        if(this.pageInfo.currentPage === 1){
          this.isPrev=true;
        }
        if(this.pageInfo.currentPage === this.pageInfo.pageCount){
          this.isNext=true;
          this.isLast=true;
        }else{
          this.isNext=false;
          this.isLast=false;
        }
      },
      /*当前页码*/
      pagingChange(){
        if(!/^[1-9]\d*$/.test(this.pageInfo.currentPage)){
          this.$message.warning({message: "请输入正整数"});
          this.pageInfo.currentPage=1;
        }
        if (this.pageInfo.pageSize * (this.pageInfo.currentPage-1) >= this.pageInfo.total) //当前分页条数大于等于总条数
          this.pageInfo.currentPage = 1;
        this.changeBarStatus();
        this.$emit("pageNumberChange", this.pageInfo.currentPage, this.pageInfo.pageSize, this.orderCode, this.orderBy);
      },
      /*第一页*/
      firstPage(){
        if(this.pageInfo.currentPage === 1)return;
        this.pageInfo.currentPage=1;
        this.pagingChange();
      },
      /*上一页*/
      prevPage(){
        if(this.pageInfo.currentPage === 1)return;
        this.pageInfo.currentPage -= 1;
        this.pagingChange();
      },
      /*下一页*/
      nextPage(){
        if(this.pageInfo.currentPage === this.pageInfo.pageCount)return;
        this.pageInfo.currentPage += 1;
        this.pagingChange();
      },
      /*最后一页*/
      lastPage(){
        if(this.pageInfo.currentPage === this.pageInfo.pageCount)return;
        this.pageInfo.currentPage = this.pageInfo.pageCount;
        this.pagingChange();
      },
      /*刷新*/
      refreshPage(){
        this.isLoading=true;
        this.$emit("pageNumberChange", this.pageInfo.currentPage, this.pageInfo.pageSize, this.orderCode, this.orderBy);
        setTimeout(()=>{
          this.isLoading=false;
        },300);
      },
      /*分页方法*/
      /*handlePageChange(cur){
        this.$emit("pageNumberChange", cur,this.pageInfo.pageSize);
      },
      prevClick(cur){
        this.$emit("pageNumberChange", cur,this.pageInfo.pageSize);
      },
      nextClick(cur){
        this.$emit("pageNumberChange", cur, this.pageInfo.pageSize);
      },
      sizeChangeClick(pageSize){
        this.$emit("pageNumberChange", this.pageInfo.currentPage, pageSize);
      },*/
      /*行--多选*/
      handleMultipleSelect(val) {
        if(!this.selectType || this.selectType === 'single') return;
        if(val) {
          this.$emit("selectRowChange", val);
        }
      },
      /*行--单选*/
      handleSingleSelect(currentRow,oldCurrentRow){
        if(!this.selectType || this.selectType === 'multiple') return;
        if(currentRow) {
          this.$emit("selectRowChange", currentRow);
        }
      },
      padLeftZero (str){
        return ('00' + str).substr(str.length);
      },
      sortChange(params){
        this.orderCode = params.prop;
        // this.orderBy = params.order=="descending"?"desc":"asc";
        if(params.order=='descending')
          this.orderBy = 'desc';
        if(params.order=='ascending')
          this.orderBy = 'asc';
        if(!params.order){
          this.orderCode='';
          this.orderBy = '';
        }
        this.$emit("pageNumberChange", this.pageInfo.currentPage, this.pageInfo.pageSize, this.orderCode, this.orderBy);
      }
    }
  }
</script>

<style>
.page-bar{
  /*text-align: left;*/
  padding-top: 8px;
}
.page-bar:after{
  clear: both;
  display: block;
  content: '';
}
.page-bar .paging-right{
  float: right;
  color: #555;
}
.page-bar .paging-size{
  width: 50px;
  height: 32px;
  text-align: center;
  border: 1px solid #06a4fe;
  color: #06a4fe;
  border-radius: 4px;
}
.page-bar img{
  cursor: pointer;
  padding-right: 16px;
}
.page-bar img.disable{
  cursor: not-allowed;
}
.page-bar img.enable{
  cursor: pointer;
}
.page-bar img:first-of-type,.page-bar img:nth-of-type(3){
  padding-left: 16px;
}
.page-bar img:last-of-type{
  padding-right: 0;
}
.page-bar .paging-left{
  float: left;
  line-height: 32px;
  color: #333;
}
/*table样式覆盖*/
.page-bar .el-input__inner{
  height: 32px !important;
}
.page-bar .el-input__icon{
  line-height: 32px !important;
}
.page-bar .paging-size .el-input__inner{
  text-align: center;
  border: 1px solid #06a4fe;
  color: #06a4fe;
}
table tr th{
  font-weight:normal;
}
</style>
